#!/bin/env python2.7
#coding:utf-8
##### code  by  mik ####
##### qiangchuan.wu ####
import psutil
import time 
from comm import SendToServer
from comm import half,SendMsg
from conf.client_conf import ClientConfig
import thread
import time



import urllib2
import json



def CPU(arg01,arg02):
    #开始使用线程
    def func(callback):
        LinuxCPU={}
         
        CpuIdle01 = psutil.cpu_times_percent().idle
        CpuIowait01 = psutil.cpu_times_percent().iowait
        CpuUser01 = psutil.cpu_times_percent().user
        CpuSystem01 = psutil.cpu_times_percent().system
        time.sleep(5)
         
        CpuIdle02 = psutil.cpu_times_percent().idle
        CpuIowait02 = psutil.cpu_times_percent().iowait
        CpuUser02 = psutil.cpu_times_percent().user
        CpuSystem02 = psutil.cpu_times_percent().system
         
        CpuIdle = half(CpuIdle01, CpuIdle02)
        CpuIowait = half(CpuIowait01, CpuIowait02)
        CpuUser  = half(CpuUser01, CpuUser02)
        CpuSystem = half(CpuSystem01, CpuSystem02)
         
        LinuxCPU['Idle'] = CpuIdle
        LinuxCPU['Iowait'] = CpuIowait
        LinuxCPU['User'] = CpuUser
        LinuxCPU['System'] = CpuSystem
         
        LinuxCPU['IPaddr'] = ClientConfig['Localip']
        print "开始执行CPU获取XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        time.sleep(10)
        print "完成CPU获取XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",LinuxCPU
#         return LinuxCPU
        callback(LinuxCPU,arg01,arg02)
    thread.start_new_thread(func, (SendMsg,))
#######################3   arg01=== Monitor/stat arg02=== LinuxCPU

# #以下为测试代码，以将此代码转移到comm公共模块中。
#     
# def SendMsg(data,arg01,arg02):
# #     arg01 = "Monitor/stat"
# #     arg02 = "LinuxCPU"
#     
#     url='http://'+ClientConfig['Service'] + ':' + ClientConfig['Port'] + '/' + arg01 + '/' + arg02+'/'
#             
#     try:
#         a=urllib2.urlopen(url,json.dumps(data))
#         for i in a:
#             print i
#             if i != 'ok':
#                 time.sleep(1)
#                 a=urllib2.urlopen(url,json.dumps(data))
#     except Exception,e:
#         print "提交数据出现错误",e
# 
# 
# 
# 
#     
#     
#     
#     